<template>
  <div id="mention-modal" :style="{ top: top, left: left }">
    <SelectWithUserLoad
      ref="userSelect"
      v-model="searchVal"
      :multiple="false"
      extend-class="mention-input-box"
      default-first-option
      input-width-is-auto
      placeholder=""
      key-name="id"
      value-type="object"
      class="mention-input"
      label-name="userName"
      filterable
      @changeMethod="handleMentionSelect"
      @getCurSearchVal="getCurSearchVal"
      @keyup.delete.native="onDelete"
    />
  </div>
</template>

<script>
import SelectWithUserLoad from '@/components/Common/selectWithUserLoad';
export default {
  name: 'MentionModal',
  components: {
    SelectWithUserLoad
  },
  props: {
    editor: {
      type: Object,
      default: () => ({})
    },
    toolbarTop: { // 工具栏底部到弹窗顶部的高度，定位@浮窗需要用到
      type: Number,
      default: 0
    },
    paddingLeft: { // 弹窗左边距，定位@浮窗需要用到
      type: Number,
      default: 25
    }
  },
  data() {
    return {
      top: '',
      left: '',

      searchVal: '',
      realTimeSearchVal: '', // 实时搜索文本
      isEmpty: true
    };
  },
  mounted() {
    // 获取光标位置
    const domSelection = document.getSelection();
    const domRange = domSelection && domSelection.getRangeAt(0);
    if (domRange == null) return;
    const rect = domRange.getBoundingClientRect();
    const containerRect = this.editor.getEditableContainer().getBoundingClientRect();
    // 定位 modal
    this.$nextTick(() => {
      this.top = `${rect.top - containerRect.top + this.toolbarTop - 5}px`;
      this.left = `${rect.left - containerRect.left + this.paddingLeft}px`;
      this.$refs['userSelect'].inputFocus();
    });
  },
  methods: {
    getCurSearchVal(val) {
      this.isEmpty = false;
      this.realTimeSearchVal = val;
    },
    onDelete() {
      if (!this.realTimeSearchVal) {
        this.isEmpty && this.$emit('closeMentionModal');
        this.isEmpty = !this.isEmpty;
      }
    },
    handleMentionSelect(selectedData) {
      this.insertMentionHandler(selectedData.id, selectedData.userName);
    },
    insertMentionHandler(id, label) {
      this.$emit('insertMention', id, label);
      this.$emit('hideMentionModal'); // 隐藏 modal
    }
  }
};
</script>
<style lang="scss">
.mention-input-box {
  min-width: 120px !important;
  .el-select-dropdown__empty {
    min-width: 120px;
  }
}
</style>
<style scoped lang="scss">
#mention-modal {
  position: absolute;
  background-color: #fff;
}
.mention-input {
  &::v-deep {
    input {
      padding: 0;
    }
    .el-input__inner {
      border-color: transparent !important;
    }
    .el-input__suffix {
      display: none;
    }
  }
}
</style>
